<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @row-save="rowSave"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button size="small" type="primary" :disabled="selectionList.length != 1" icon="el-icon-edit" @click="handleUpdate" v-if="permission.quality_template_edit"
          >编 辑</el-button
        >
        <el-button
          size="small"
          type="primary"
          :disabled="selectionList.length != 1"
          icon="el-icon-view"
          @click="selectItem(row, 'view')"
          v-if="permission.qualityTemplate_config"
          >查 看</el-button
        >
        <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDelete" v-if="permission.quality_template_delete">删 除</el-button>
      </template>
      <template slot="menu" slot-scope="{ row }">
        <el-button size="small" type="text" @click="selectItem(row, 'config')" v-if="permission.qualityTemplate_config">配置检验项</el-button>
        <el-button size="small" type="text" @click="templateApplication(row)" v-if="permission.qualityTemplate_apply">模板应用</el-button>
        <!-- <el-button size="small" type="text" icon="el-icon-view" @click="selectItem(row, 'view')" v-if="permission.qualityTemplate_config">查看</el-button> -->
      </template>
    </avue-crud>
    <el-dialog append-to-body :visible.sync="showDialog" width="60%" :fullscreen="fullscreenDialog">
      <div slot="title">
        编辑检验模板
        <i class="el-dialog__close fill-screen-icon" :class="fullscreenDialog ? 'el-icon-news' : 'el-icon-full-screen'" @click="fullscreenDialog = !fullscreenDialog"></i>
      </div>
      <avue-form ref="properties" v-model="model" :option="propertiesOption"> </avue-form>
      <div slot="footer">
        <el-button type="primary" size="small" icon="el-icon-circle-check" @click="updateTemplate">修 改</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--选择检验项弹框-->
    <el-dialog title="选择检验项" v-if="showCheckDialog" :key="key" :fullscreen="fullscreenCheckDialog" append-to-body :visible.sync="showCheckDialog" width="70%">
      <div slot="title">
        {{ viewDisplay ? '选择检验项' : '查看检验项' }}
        <i
          class="el-dialog__close fill-screen-icon"
          :class="fullscreenCheckDialog ? 'el-icon-news' : 'el-icon-full-screen'"
          @click="fullscreenCheckDialog = !fullscreenCheckDialog"
        ></i>
      </div>
      <el-tabs type="card" v-model="tabsIndex" @tab-click="handleTabClick($event)" v-if="!viewDisplay">
        <el-tab-pane label="查看检验项" name="1"> </el-tab-pane>
        <el-tab-pane v-if="permission.qualityTemplate_apply" label="模板应用" name="2"></el-tab-pane>
      </el-tabs>
      <avue-crud
        v-if="tabsIndex === '1'"
        ref="inspectionProperties"
        :option="itemOption"
        :table-loading="loading"
        v-model="itemObj"
        :data="itemData"
        :page.sync="itemPage"
        @current-change="currentItemChange"
        @size-change="sizeItemChange"
        @selection-change="selectionItemChange"
        @select-all="selectAll"
        @search-change="searchItemChange"
        @select="selectChange"
        @search-reset="searchItemReset"
        :key="key"
      >
      </avue-crud>
      <!-- <avue-form ref="properties" v-model="templeteForm" :option="templeteOption" v-if="tabsIndex === '2'">
        <template slot-scope="{}" slot="radio">
          <avue-radio v-model="templeteForm.objectType" :dic="dic"></avue-radio>
        </template>
      </avue-form> -->
      <avue-crud v-if="tabsIndex === '2'" :option="templateOption" :data="templateData">
        <template slot-scope="{ row }" slot="isDefault">
          <el-tag :class="row.isDefault ? 'successTag' : 'dangerTag'">{{ row.isDefault ? '是' : '否' }}</el-tag>
        </template>
      </avue-crud>

      <div slot="footer" v-if="viewDisplay">
        <el-button type="primary" size="small" icon="el-icon-circle-check" @click="nextStep"
          >下一步
          <!-- <i class="el-icon-right"></i> -->
        </el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="cancelSaveTemplateAttributes">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="检验项排序" v-if="sortableDialog" :fullscreen="fullscreenCheckDialog" append-to-body :visible.sync="sortableDialog" width="70%">
      <div slot="title">
        检验项排序
        <i
          class="el-dialog__close fill-screen-icon"
          :class="fullscreenCheckDialog ? 'el-icon-news' : 'el-icon-full-screen'"
          @click="fullscreenCheckDialog = !fullscreenCheckDialog"
        ></i>
      </div>
      <avue-crud v-if="sortableDialog" ref="sortableProperties" :option="sortableOption" :data="sortableData" :key="key">
        <template slot="icon">
          <div style="display: flex; justify-content: center"><span class="iconfont icon-c088tuozhuai"></span></div
        ></template>
        <template slot="iconHeader">
          <div style="display: flex; justify-content: center"><span class="iconfont icon-c088tuozhuai"> </span></div
        ></template>
      </avue-crud>
      <div slot="footer">
        <el-button type="primary" size="small" icon="el-icon-circle-check" @click="saveTemplateAttributes"
          >提交
          <!-- <i class="el-icon-right"></i> -->
        </el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="cancelSaveTemplateAttributes2">上一步</el-button>
      </div>
    </el-dialog>
    <!--模板检验项详情-->
    <!-- <el-dialog append-to-body :visible.sync="showTemplateDialog" width="70%" :show-close="false" :fullscreen="fullscreenTemplateDialog">
      <div slot="title" style="font-size: 18px">
        编辑检验项<span class="close-dialog">
          <i
            class="el-dialog__close fill-screen-edit-icon"
            :class="fullscreenTemplateDialog ? 'el-icon-news' : 'el-icon-full-screen'"
            @click="fullscreenTemplateDialog = !fullscreenTemplateDialog"
          ></i>
          <i class="el-icon-close" @click="closeDialog"></i
        ></span>
      </div>
      <el-row>
        <el-col :span="4">
          <div style="color: rgb(28, 138, 254); font-size: 12px">检验项列表</div>
          <div class="icon-inspection-item">
            <el-button class="refresh-btn inspection-btn" size="small" icon="el-icon-refresh" @click="refreshInspection"></el-button>
            <el-button class="add-btn inspection-btn" size="small" icon="el-icon-plus" @click="addInspection"></el-button>
            <el-button
              :disabled="!selectItemId"
              class="inspection-btn"
              :class="selectItemId ? 'edit-btn' : 'btn-disabled'"
              size="small"
              icon="el-icon-edit"
              @click="updateInspection"
            ></el-button>
            <el-button
              :disabled="!selectItemId"
              class="inspection-btn"
              :class="selectItemId ? 'del-btn' : 'btn-disabled'"
              size="small"
              icon="el-icon-close"
              @click="removeInspection"
            ></el-button>
          </div>
          <el-tree
            key="item"
            highlight-current
            default-expand-all
            :default-expanded-keys="expandedAttributeKeys"
            :option="treeOption"
            ref="treeProperties"
            :data="selectTreeData"
            @node-click="selectTreeNodeClick"
            node-key="id"
          ></el-tree>
        </el-col>
        <el-col :span="20">
          <div style="margin-left: 10px">
            <div><span style="color: #1c8afe; font-size: 12px">检验项明细</span></div>
            <avue-crud :option="attributeOption" v-model="attributeModel" :data="attributeData" ref="attributeCrud" @selection-change="selectionAttributeChange">
              <template slot="menuLeft">
                <el-button type="primary" :disabled="!selectItemId" size="small" icon="el-icon-plus" @click="addAttribute()">添加</el-button>
                <el-button size="small" type="primary" :disabled="selectionAttributeList.length != 1" icon="el-icon-edit" @click="updateAttribute">编辑</el-button>
                <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteAttribute()">删 除 </el-button>
              </template>
            </avue-crud>
          </div>
        </el-col>
      </el-row>
      <div slot="footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="cancelShowTemplateDetail">提交</el-button>
      </div>
    </el-dialog> -->

    <!--新增或者编辑检验明细-->
    <el-dialog append-to-body :visible.sync="showAttributeDialog" width="60%" :fullscreen="fullscreenAttributeDialog">
      <div slot="title">
        {{ attributeTitle }}
        <i
          class="el-dialog__close fill-screen-icon"
          :class="fullscreenAttributeDialog ? 'el-icon-news' : 'el-icon-full-screen'"
          @click="fullscreenAttributeDialog = !fullscreenAttributeDialog"
        ></i>
      </div>
      <avue-form ref="attributeProperties" v-model="attributeTemplateModel" :option="attributeTemplateOption">
        <template slot="controlType">
          <div class="group-title"><i class="el-icon-vertical-bar avue-group__icon" style="cursor: not-allowed"></i>控件配置</div>
          <div style="width: 35vw">
            <div style="display: inline-block; margin: 0 30px 20px 10px; font-weight: bold; color: #606266">
              <span>控件类型: </span>
            </div>
            <div style="display: inline-block">
              <el-select :disabled="disabledAttributeControl" @change="changeControlType" v-model="attributeTemplateModel.controlType.type" clearable placeholder="请选择">
                <el-option v-for="item in controlTypes" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"> </el-option>
              </el-select>
            </div>
            <div style="margin-left: 10px">
              <el-row>
                <el-col :span="16">
                  <div v-for="(item, index) in attributeTemplateModel.controlType.options" :key="index">
                    <el-row
                      style="margin-bottom: 10px"
                      v-if="attributeTemplateModel.controlType.type === 'SINGLE-INPUT' || attributeTemplateModel.controlType.type === 'MULTIPLE-INPUT'"
                    >
                      <el-col :span="10" style="margin-right: 30px">
                        <el-input :disabled="disabledAttributeControl" maxlength="15" placeholder="请输入内容" v-model="item.label" clearable> </el-input>
                      </el-col>
                      <el-col :span="11">
                        <el-select :disabled="disabledAttributeControl" v-model="item.type" placeholder="请选择输入框类型">
                          <el-option v-for="item in inputTypes" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                        </el-select>
                      </el-col>
                      <el-col :span="1">
                        <i style="margin-left: 10px" class="el-icon-delete delete-controlType" @click="deletecontrolType(index)"></i>
                      </el-col>
                    </el-row>
                    <el-row style="margin-bottom: 10px" v-if="attributeTemplateModel.controlType.type === 'RADIO'">
                      <el-col :span="14" style="margin-right: 20px">
                        <el-input :disabled="disabledAttributeControl" maxlength="15" placeholder="请输入内容" v-model="item.label" clearable> </el-input>
                      </el-col>
                      <el-col :span="8">
                        <el-row>
                          <el-col :span="2">
                            <el-radio label=""></el-radio>
                          </el-col>
                          <el-col :span="7">
                            <span style="padding-left: 10px"> {{ item.realLabel }}</span>
                            <!-- <el-input placeholder="判断1" maxlength="15" :disabled="disabledAttributeControl" v-model="item.realLabel" clearable> </el-input> -->
                          </el-col>
                          <el-col :span="2" style="margin-left: 10px">
                            <el-radio label=""></el-radio>
                          </el-col>
                          <el-col :span="7">
                            <span style="padding-left: 10px"> {{ item.shamLabel }}</span>
                            <!-- <el-input placeholder="判断2" maxlength="15" :disabled="disabledAttributeControl" v-model="item.shamLabel" clearable> </el-input> -->
                          </el-col>
                          <el-col :span="3">
                            <i style="margin-left: 10px" class="el-icon-delete delete-controlType" @click="deletecontrolType(index)"></i>
                          </el-col>
                        </el-row>
                      </el-col>
                    </el-row>
                  </div>
                  <template v-if="attributeTemplateModel.controlType.type === 'SINGLE-INPUT' || attributeTemplateModel.controlType.type === 'RADIO'">
                    <div style="color: #009dd9; font-size: 12px; cursor: pointer">
                      <i class="el-icon-circle-plus-outline" @click="addOption(attributeTemplateModel.controlType.type)">
                        {{ attributeTemplateModel.controlType.type === 'SINGLE-INPUT' ? '添加输入项' : '添加判断项' }}
                      </i>
                    </div>
                  </template>
                </el-col>
                <el-col :span="7" style="margin-left: 10px" v-if="attributeTemplateModel.controlType.type">
                  <el-row style="width: 15vw">
                    <el-col :span="4"><span style="color: #b0b0b0">示例：</span></el-col>
                    <template v-if="attributeTemplateModel.controlType.type === 'SINGLE-INPUT'">
                      <el-col :span="6"> 检验数量: </el-col>
                      <el-col :span="14">
                        <el-input readonly placeholder="请输入内容"></el-input>
                      </el-col>
                    </template>

                    <template v-if="attributeTemplateModel.controlType.type === 'MULTIPLE-INPUT'">
                      <el-col :span="6"> 测试值: </el-col>
                      <el-col :span="14">
                        <el-input readonly placeholder="请输入内容"></el-input>
                      </el-col>
                    </template>
                    <template v-if="attributeTemplateModel.controlType.type === 'RADIO'">
                      <el-col :span="10"> 是否按检验标准: </el-col>
                      <el-col :span="10">
                        <el-radio label="">是</el-radio>
                        <el-radio label="">否</el-radio>
                      </el-col>
                    </template>
                  </el-row>
                  <el-row style="width: 15vw; margin-top: 5px">
                    <template v-if="attributeTemplateModel.controlType.type === 'SINGLE-INPUT'">
                      <el-col :span="10"> <span style="float: right; margin-right: 5px">不良数量:</span> </el-col>
                      <el-col :span="14">
                        <el-input readonly placeholder="请输入内容"></el-input>
                      </el-col>
                    </template>
                  </el-row>
                  <div style="margin-left: 25%; color: #009dd9; font-size: 12px">
                    <template>
                      <el-button type="text" @click="openExample"> 查看页面示例</el-button>
                    </template>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </template>
      </avue-form>
      <div slot="footer">
        <el-button
          type="primary"
          size="small"
          :icon="attributeTitle == '添加检验明细项' ? 'el-icon-circle-plus-outline' : 'el-icon-circle-check'"
          @click="submitAttribute"
          v-preventReClick
          >{{ attributeTitle == '添加检验明细项' ? '保 存' : '修 改' }}</el-button
        >
        <el-button size="small" icon="el-icon-circle-close" @click="cancelAttribute">取 消</el-button>
      </div>
    </el-dialog>

    <!--新增、编辑模板检验项-->
    <el-dialog append-to-body :visible.sync="showInspectionDialog" width="30%" :fullscreen="fullscreenInspectionDialog">
      <div slot="title">
        {{ inspectionTitle }}
        <i
          class="el-dialog__close fill-screen-icon"
          :class="fullscreenInspectionDialog ? 'el-icon-news' : 'el-icon-full-screen'"
          @click="fullscreenInspectionDialog = !fullscreenInspectionDialog"
        ></i>
      </div>
      <avue-form ref="inspectionTemplateProperties" v-model="inspectionModel" :option="inspectionOption"> </avue-form>
      <div slot="footer">
        <el-button
          type="primary"
          size="small"
          :icon="inspectionTitle == '添加检验项' ? 'el-icon-circle-plus-outline' : 'el-icon-circle-check'"
          @click="submitInspection"
          v-preventReClick
          >{{ inspectionTitle == '添加检验项' ? '保 存' : '修 改' }}</el-button
        >
        <el-button size="small" icon="el-icon-circle-close" @click="cancelInspection">取 消</el-button>
      </div>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="key" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, save, remove, saveInspection, getTreeById, getInspectionTemattribute } from '@/api/quality/quality-template-manage';
import {
  getSelectattributeList,
  getInspectionlist,
  getInspectionitemattributeList,
  removeInspectionitem,
  addInspectionitem,
  getControlType,
  getInspectionDetail,
  addOrUpdateInspection,
  getInspectionitemattributeDetail,
  delInspection
} from '@/api/quality/quality-manage';

import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

export default {
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    const operationTypes = [
      {
        label: '人员',
        value: 'PERSONNEL'
      },
      {
        label: '机器',
        value: 'MACHINE'
      },
      {
        label: '材料',
        value: 'MATERIAL'
      },
      {
        label: '方法',
        value: 'METHOD'
      },
      {
        label: '测量',
        value: 'MEASURE'
      },
      {
        label: '环境',
        value: 'ENVIRONMENT'
      }
    ];
    const testTypes = [
      {
        label: '正常',
        value: 'NORMAL'
      },
      {
        label: '主要',
        value: 'MAJOR'
      },
      {
        label: '次要',
        value: 'MINOR'
      }
    ];
    const inspectionTypes = [
      {
        label: 'IQC',
        value: 'IQC'
      },
      {
        label: 'OQC',
        value: 'OQC'
      },
      {
        label: 'IPQC',
        value: 'IPQC'
      },
      {
        label: 'FQC',
        value: 'FQC'
      }
    ];
    return {
      pageCode: 'QUALITY_TEMPLATE_MANAGE',
      tableOption: {},
      modalName: '',
      templateOption: {
        addBtn: false,
        columnBtn: false,
        labelWidth: '130',
        refreshBtn: false,
        menu: false,
        border: true,
        column: [
          {
            label: '对象类型',
            prop: 'objectType',
            type: 'select',
            dicData: [
              {
                label: '物料类型',
                value: 'PART_CATEGORY'
              },
              {
                label: '物料',
                value: 'PART_MASTER'
              }
            ]
          },
          {
            label: '选择编码',
            prop: 'code'
          },
          {
            label: '选择名称',
            prop: 'name'
          },
          {
            label: '是否默认',
            prop: 'isDefault',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          }
        ]
      },
      fullscreenCheckDialog: false, //选则检验项弹框是否全屏
      fullscreenTemplateDialog: false, //配置检验项是否全屏
      fullscreenAttributeDialog: false, //检验明细项是否全屏
      fullscreenInspectionDialog: false, //树图标检验项是否全屏
      fullscreenDialog: false,
      selectInspectionType: 'auto', //检验项明细触发方式，有两种，一种为click，点击复选框触发，另一种为自动关联触发
      selectionItemType: 'auto',
      selectInspection: {},
      dataTest: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      itemType: '',
      form: {},
      key: new Date().getTime(),
      viewDisplay: false,
      model: {},
      templateData: [],
      query: { status: 1 },
      itemQuery: {},
      templateIds: [],
      templeteForm: {},
      loading: true,
      itemLoading: true,
      selcetLock: false,
      sortableDialog: false,
      sortableOption: {
        sortable: true,
        // dropRowClass: '.icon',
        // // dropColClass: '.el-table-column--selection',
        // // ghostClass: 'iconfont',
        tip: false,
        searchShow: false,
        border: true,
        index: false,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        selection: false,
        dialogClickModal: false,
        menu: false, //是否显示操作栏
        column: [
          {
            label: '11',
            prop: 'icon',
            width: 50,
            slot: true
          }
        ]
      },
      sortableData: [],
      templateModel: {
        //存储检验模板对应的模板与检验项
        attributeIdList: [],
        attributeList: [],
        itemIdList: [],
        templateId: ''
      },
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      itemPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      selectionAttributeList: [],
      data: [],
      selectData: [],
      code: '00',
      searchLabelWidth: 100,
      checkIqc: true,
      tabsIndex: '1',
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        addTitle: '添加检验模板',
        addBtnText: '添加',
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: true,
        delBtn: false,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        labelWidth: 130,
        searchLabelWidth: 130,
        menuWidth: 200,
        indexLabel: '序号',
        columnBtn: false,
        column: [
          {
            label: '模板类型',
            prop: 'type',
            search: true,
            type: 'select',
            span: 8,
            dicUrl: '/api/blade-system/dict/dictionary?code=QC',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请选择区域类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验模板编码',
            prop: 'code',
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入检验模板编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验模板名称',
            prop: 'name',
            span: 8,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入检验模板名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '版本号',
            prop: 'revision',
            span: 8
          },
          {
            label: '检验模板报告',
            prop: 'reportTemplateName',
            span: 8,
            row: true,
            type: 'search',
            disabled: true,
            hide: true,
            labelTip: '若未选择，则默认系统标准检验报告模板',
            appendClick: () => {
              this.openInspectionReportModal('ADD');
            }
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            span: 10
          },
          {
            label: '制定人',
            prop: 'createUserName',
            display: false
          },
          {
            label: '制定时间',
            prop: 'createTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            display: false
          }
        ]
      },
      timer: null,
      key: new Date().getTime(),
      showDialog: false,
      propertiesOption: {
        emptyBtn: false,
        submitBtn: false,
        labelWidth: 120,
        column: [
          {
            label: '模板类型',
            prop: 'type',
            type: 'select',
            disabled: true,
            span: 8,
            dicUrl: '/api/blade-system/dict/dictionary?code=QC',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请选择区域类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验模板名称',
            prop: 'name',
            span: 8,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入检验模板名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验模板编码',
            prop: 'code',
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入检验模板编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '版本号',
            prop: 'revision',
            span: 8
          },
          {
            label: '检验模板报告',
            prop: 'reportTemplateName',
            span: 8,
            row: true,
            type: 'search',
            disabled: true,
            hide: true,
            labelTip: '若未选择，则默认系统标准检验报告模板',
            appendClick: () => {
              this.openInspectionReportModal('EIDT');
            }
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            span: 10
          }
        ]
      },
      expandedKeys: [], //默认展开的节点
      showCheckDialog: false, //展示选择dialog
      checkedKeys: [], //默认勾选的检查项
      checkTreeData: [], //选择检验项树
      checkTreeOption: {
        //选择检验项配置
        nodeKey: 'id',
        lazy: false,
        menu: false,
        filter: false,
        size: 'small',
        props: {
          labelText: '标题',
          label: 'label',
          value: 'value',
          children: 'children'
        }
      },
      itemObj: {},
      itemData: [], //检验项明细列表
      itemOption: {
        height: 500,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        selection: true,
        dialogClickModal: false,
        labelWidth: 120,
        searchLabelWidth: 110,
        searchMenuPosition: 'right',
        menu: false, //是否显示操作栏
        column: [
          {
            label: '检验模板类型',
            prop: 'itemType',
            type: 'select',
            // search: true,
            dicData: [
              {
                label: 'IQC',
                value: 'IQC'
              },
              {
                label: 'LAI',
                value: 'LAI'
              },
              {
                label: 'IPQC',
                value: 'IPQC'
              },
              {
                label: 'FQC',
                value: 'FQC'
              },
              {
                label: 'OQC',
                value: 'OQC'
              },
              {
                label: 'FAI',
                value: 'FAI'
              },
              {
                label: 'MI',
                value: 'MI'
              }
            ]
          },
          {
            label: '检验项',
            prop: 'itemName',
            search: true,
            labelWidth: 100,
            type: 'tree',
            checkStrictly: true,
            dicUrl: '/api/mes-product/qms-inspection-item/selectTree',
            span: 20,
            props: {
              label: 'itemName',
              value: 'itemName'
            },
            dicFormatter: ({ data }) => {
              let itemName = [];
              this._forEach(data, (item) => {
                if (item.itemType === this.itemType) {
                  itemName = item.itemList;
                }
              });
              return itemName;
            }
          },
          {
            label: '检验项明细',
            prop: 'attributeName',
            search: true
          },
          {
            label: '明细项编码',
            prop: 'code',
            search: true
          },
          {
            label: '检验标准',
            prop: 'testCriterion',
            rules: [
              {
                required: true,
                message: '请输入物料编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验类型',
            prop: 'testType',
            type: 'select',
            dicData: testTypes
          },
          {
            label: '质量因素',
            prop: 'operationType',
            type: 'select',
            dicData: operationTypes,
            width: 80
          },
          {
            label: '检验方式',
            prop: 'testRecordType',
            dicData: [
              {
                label: '检验',
                value: 'INSPECTION'
              },
              {
                label: '测试',
                value: 'TEST'
              }
            ],
            rules: [
              {
                required: true,
                message: '请输入检验方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验工具',
            prop: 'testTool',
            rules: [
              {
                required: true,
                message: '请输入检验工具',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '控件类型',
            prop: 'controlTypeLabel',
            width: 120
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      showTemplateDialog: false, //检验模板对应的详情
      selectTreeData: [], //模板选择的检验树
      expandedSelectKeys: [],
      attributeOption: {
        height: 500,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        menu: false,
        addBtn: false,
        delBtn: false,
        viewBtn: false,
        editBtn: false,
        selection: true,
        refreshBtn: false,
        columnBtn: false,
        dialogClickModal: false,
        labelWidth: 120,
        menuWidth: 100,
        searchLabelWidth: 90,
        menuWidth: 200,
        column: [
          {
            label: '检验项明细',
            prop: 'attributeName'
          },
          {
            label: '明细项编码',
            prop: 'code'
          },
          {
            label: '检验标准',
            prop: 'testCriterion',
            rules: [
              {
                required: true,
                message: '请输入物料编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验类型',
            prop: 'testType',
            type: 'select',
            dicData: testTypes
          },
          {
            label: '质量因素',
            prop: 'operationType',
            type: 'select',
            dicData: operationTypes,
            width: 80
          },
          {
            label: '检验方式',
            prop: 'testRecordType',
            dicData: [
              {
                label: '检验',
                value: 'INSPECTION'
              },
              {
                label: '测试',
                value: 'TEST'
              }
            ],
            rules: [
              {
                required: true,
                message: '请输入检验方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验工具',
            prop: 'testTool',
            rules: [
              {
                required: true,
                message: '请输入检验工具',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '控件类型',
            prop: 'controlTypeLabel',
            width: 120
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      attributeData: [],
      attributeModel: {},
      treeOption: {
        //选择检验项配置
        nodeKey: 'id',
        lazy: false,
        menu: false,
        filter: false,
        size: 'small',
        props: {
          labelText: '标题',
          label: 'label',
          value: 'value',
          children: 'children'
        }
      },
      selectItemId: '',
      attributeTitle: '',
      showAttributeDialog: false,
      attributeTemplateModel: {
        controlType: {
          type: '',
          options: []
        }
      },
      attributeTemplateOption: {
        label: '基本信息',
        icon: 'el-icon-vertical-bar',
        arrow: false,
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: '检验项明细',
            prop: 'attributeName',
            labelWidth: 100,
            maxlength: 50,
            span: 8,
            type: 'input',
            rules: [
              {
                required: true,
                message: '请输入检验项明细',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '明细项编码',
            prop: 'code',
            labelWidth: 100,
            maxlength: 50,
            span: 8,
            type: 'input',
            rules: [
              {
                required: true,
                message: '请输入明细项编码',
                trigger: 'blur'
              }
            ]
          },

          {
            label: '检验类型',
            span: 8,
            type: 'select',
            dicData: testTypes,
            prop: 'testType'
          },
          {
            label: '检验标准',
            prop: 'testCriterion',
            maxlength: 15,
            span: 8,
            type: 'input'
          },

          {
            label: '质量因素',
            span: 8,
            prop: 'operationType',
            type: 'select',
            dicData: operationTypes
          },
          {
            label: '检验方式',
            span: 8,
            prop: 'testRecordType',
            type: 'select',
            dicData: [
              {
                label: '检验',
                value: 'INSPECTION'
              },
              {
                label: '测试',
                value: 'TEST'
              }
            ]
          },
          {
            label: '检验工具',
            span: 8,
            prop: 'testTool',
            maxlength: 50
          },
          {
            label: '备注/原因',
            prop: 'remark',
            span: 24,
            type: 'textarea',
            maxlength: 50,
            maxRows: 3,
            minRows: 3
          },
          {
            label: '',
            span: 24,
            labelWidth: 0,
            formslot: true,
            prop: 'controlType'
          }
        ]
      },
      disabledAttributeControl: false,
      expandedAttributeKeys: [], //检验模板对应的检验项展开列表ids
      controlTypeOptions: {
        //存储不同类型组件options
        inputOptions: [],
        radioOptions: [],
        multipleOptions: []
      },
      inputTypes: [
        {
          label: '数字框',
          value: 'number'
        },
        {
          label: '文本框',
          value: 'string'
        }
      ],
      controlTypes: [], //控件类型
      inspectionTitle: '',
      showInspectionDialog: false,
      inspectionModel: {}, //检查项对象，
      inspectionOption: {
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: '检验项类型',
            prop: 'itemType',
            labelWidth: 100,
            span: 20,
            type: 'select',
            dicData: inspectionTypes,
            rules: [
              {
                required: true,
                message: '请选择检验项类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验项名称',
            prop: 'itemName',
            labelWidth: 100,
            span: 20,
            type: 'input',
            rules: [
              {
                required: true,
                message: '请输入检验项名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验项编码',
            span: 20,
            labelWidth: 100,
            prop: 'code',
            rules: [
              {
                required: true,
                message: '请输入检验项编码',
                trigger: 'blur'
              }
            ]
          }
        ]
      }
    };
  },
  watch: {},
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.quality_template_add, false),
        viewBtn: this.vaildData(this.permission.quality_template_view, false),
        delBtn: this.vaildData(this.permission.quality_template_delete, false),
        editBtn: this.vaildData(this.permission.quality_template_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    this.getControlTypes();
  },
  methods: {
    /**
     * 查询数据字典控件类型
     */
    getControlTypes() {
      getControlType()
        .then((res) => {
          if (res.data.code === 200) {
            this.controlTypes = res.data.data;
          }
        })
        .catch((err) => {});
    },
    //新增检验项模板
    rowSave(form, done, loading) {
      save(form).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },

    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          // 刷新表格数据并重载
          this.data = [];
          this.parentId = 0;
          this.$refs.crud.refreshTable();
          this.$refs.crud.toggleSelection();
          // 表格数据重载
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },

    handleUpdate() {
      this.model = {};
      if (this.selectionList.length === 1) {
        let id = this.selectionList[0].id;
        getDetail(id).then((res) => {
          this.model = res.data.data || {};
          this.showDialog = true;
          this.fullscreenDialog = false;
        });
      }
    },
    /**
     * 更新检验模板
     */
    async updateTemplate() {
      let attribute = this.model;
      let done;
      let validDate = await new Promise((resolve, reject) => {
        this.$refs.properties.validate((valid, done) => {
          done = done;
          if (valid) {
            resolve();
            done();
          } else {
          }
        });
      });
      Promise.all([validDate]).then(() => {
        save(attribute).then(
          () => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.showDialog = false;
          },
          (error) => {
            window.console.log(error);
          }
        );
        done();
      });
    },

    newKey() {
      this.key = new Date().getTime();
    },

    /**
     * id:string,检验模板id
     * 为检验模板选择检验项
     */
    async selectItem(row, title) {
      if (this.selectionList.length === 1) {
        row = this.selectionList[0];
      }
      this.tabsIndex = '1';
      this.newKey();
      let itemNameCol = this.findObject(this.itemOption.column, 'itemName');
      let attributeNameCol = this.findObject(this.itemOption.column, 'attributeName');
      let codeCol = this.findObject(this.itemOption.column, 'code');
      this.itemType = row.type;
      this.itemPage.total = 0;
      this.itemPage.currentPage = 1;
      this.itemPage.pageSize = 15;
      if (title === 'view') {
        this.viewDisplay = false;
        await this.getSelectedList(row.id);
        itemNameCol.search = false;
        attributeNameCol.search = false;
        codeCol.search = false;
        this.itemOption.selection = false;
        getDetail(this.selectionList[0].id).then((res) => {
          let data = res.data.data;
          this._forEach(data.partQcTemplateList || [], (item) => {
            if (item.objectType === 'PART_CATEGORY') {
              item.code = item.partCategoryCode;
              item.name = item.partCategoryName;
            } else {
              item.code = item.partNo;
              item.name = item.partName;
            }
          });
          this.templateData = data.partQcTemplateList || [];
        });
      } else {
        this.viewDisplay = true;
        await this.getSelectedList(row.id);
        itemNameCol.search = true;
        attributeNameCol.search = true;
        codeCol.search = true;
        this.itemOption.selection = true;
        this.getInspectionItemData(this.itemPage);
      }
      this.itemQuery = {};
      this.templateModel.templateId = row.id;
      this.showCheckDialog = true;
      this.fullscreenCheckDialog = false;
      this.$nextTick(() => {
        this.$refs.inspectionProperties.refreshTable();
      });
    },
    handleTabClick({ index }) {
      // console.log(index, 33333333);
      // if (Number(index) === 2) {
      // }
    },
    templateApplication(row) {
      this.$router.push({
        path: `/quality/inspect-template-application`,
        query: {
          templateIdName: encodeURI(row.name),
          templateId: row.id,
          type: row.type,
          code: encodeURI(row.code)
        }
      });
    },

    async getSelectedList(id) {
      let templateAttributes = await getSelectattributeList({ inspectionTemplateId: id, itemType: this.itemType }); //获取模板id对应的检验项列表
      this.templateModel.attributeList = templateAttributes.data.data.filter((item) => item.checked);
      this.templateModel.attributeIdList = templateAttributes.data.data.filter((item) => item.checked).map((item) => item.id);
      this.templateIds = templateAttributes.data.data.map((item) => item.id);
      if (!this.viewDisplay) {
        this.itemData = this.templateModel.attributeList;
      }
    },

    async initTree(id) {
      // this.checkTreeData = [];
      // this.checkedKeys = [];
      // this.expandedKeys = [];
      // this.itemData = [];
      // let templateAttributes = await getSelectattributeList({ templateId: id, itemType: this.itemType }); //获取模板id对应的检验项列表
      // this.templateModel.attributeList = templateAttributes.data.data.filter((item) => item.checked);
      // this.templateIds = templateAttributes.data.data.map((item) => item.id);
      // getTreeById().then(async (res) => {
      //   this.templateModel.attributeIdList = templateAttributes.data.data.filter((item) => item.checked).map((item) => item.id); //存放之前保存的attributeId
      //   this.checkTreeData = (res.data.data || []).map((item) => {
      //     let children = (item.itemList || []).map((itemChild) => {
      //       itemChild.checked ? this.checkedKeys.push(itemChild.id) : '';
      //       return {
      //         id: itemChild.id,
      //         label: itemChild.itemName,
      //         value: itemChild,
      //         leaf: true
      //       };
      //     });
      //     let treeItem = {
      //       leaf: false,
      //       value: item.itemType,
      //       label: item.itemType,
      //       // id: item.dict.id,
      //       disabled: true,
      //       children
      //     };
      //     return treeItem;
      //   });
      //   this.expandedKeys = this.templateModel.itemIdList = this.checkedKeys;
      //   // await this.getInspectionItemData(this.itemPage);
      //   //默认展示第一项列表数据
      //   // if (this.templateModel.itemIdList.length > 0) {
      //   //   this.showDefaultAttributes(this.templateModel.itemIdList[0], this.templateModel.templateId);
      //   // }
      // });
    },

    async getInspectionItemData(page, params = {}) {
      this.itemLoading = true;
      params.itemType = this.itemType;
      let result = await getInspectionTemattribute(page.currentPage, page.pageSize, Object.assign(params, this.itemQuery));
      this.itemData = ((result.data && result.data.data.records) || []).map((item) => {
        item.controlType = typeof item.controlType === 'string' ? JSON.parse(item.controlType) : item.controlType;
        let controlType = this.controlTypes.find((type) => type.dictKey === item.controlType.type);
        item.controlTypeLabel = (controlType && controlType.dictValue) || '';
        return item;
      });
      this.itemLoading = false;
      console.log(this.itemData, this.templateModel.attributeIdList, 'getInspectionItemData');
      if (this.itemData.length > 0 && this.templateModel.attributeIdList.length > 0) {
        this.markItem();
      }
      this.itemPage.total = result.data.data.total;
    },

    markItem() {
      this.$nextTick(() => {
        //取交集
        let selectData = this._intersectionWith(this.itemData, this.templateModel.attributeIdList, (item, attrId) => {
          return item.id === attrId;
        });
        console.log(selectData, 'selectData', this.templateModel.attributeIdList, this.itemData);
        selectData.forEach((row) => {
          this.$refs.inspectionProperties.toggleRowSelection(row);
        });
      });
    },

    /**
     *
     * @param {Object} node  复选框点击的对象
     * @param {*} isChecked  节点是否被选中
     * @param {*} otherChecked  节点的子树中是否有被选中的节点
     */
    async checkChange(node, isChecked, otherChecked) {
      console.log('tree change', this.selectInspectionType);
      if (this.selectInspectionType === 'click') {
        this.selectInspectionType = 'auto';
        this.selectInspection = {};
        return;
      }
      //需要展示该检验项对应的检验项明细列表并且选中
      if (isChecked) {
        // let result = await this.getInspectionItems(node.id, this.templateModel.templateId);
        this.getInspectionItemData(this.itemQuery, { itemId: node.id });
        console.log('isChecked', isChecked);
        // this.itemData = ((result.data && result.data.data) || []).map((item) => {
        //   item.controlType = JSON.parse(item.controlType);
        //   let controlType = this.controlTypes.find((type) => type.dictKey === item.controlType.type);
        //   item.controlTypeLabel = (controlType && controlType.dictValue) || '';
        //   return item;
        // });
        //防止重复存入id
        let index = this.templateModel.itemIdList.findIndex((id) => id === node.id);
        index < 0 ? this.templateModel.itemIdList.push(node.id) : '';
        this.$nextTick(() => {
          this.itemData.forEach((row) => {
            this.$refs.inspectionProperties.toggleRowSelection(row);
          });
        });
      } else {
        //去除此id
        this.templateModel.itemIdList = this.templateModel.itemIdList.filter((id) => id != node.id);
        this.$refs.inspectionProperties.toggleSelection();
      }
    },

    // 当用户手动勾选数据行的Checkbox时触发的事件
    selectChange(selection, row) {
      console.log('selectChange');
      this.selectionItemType = 'click';
      this.selectInspection = row;
      this.selcetLock = true;
      // let flag = this.templateIds.some((id) => {
      //   return id === this.selectInspection.id;
      // });
      // console.log('click');
      // if (!flag) {
      //   this.selcetLock = false; //防止走此方法selectionItemChange
      //   this.$message({
      //     type: 'warning',
      //     message: '没有与之匹配的检验模板!'
      //   });
      //   this.$refs.inspectionProperties.toggleRowSelection(this.selectInspection);
      //   return;
      // }
    },

    //勾选检验明细发生变化
    selectionItemChange(selectItems) {
      console.log('selectionItemChange', this.selcetLock);
      if (this.selcetLock) {
        this.selcetLock = false;
        if (this.timer) clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          // this.templateModel.attributeIdList = this._differenceWith(this.templateModel.attributeIdList, this.itemData, (id, item) => {
          //   return id === item.id;
          // });
          // let selectIds = selectItems.map((item) => item.id);
          // this.templateModel.attributeIdList = this.templateModel.attributeIdList.concat(selectIds);
          if (this.selectionItemType === 'click' && this.selectInspection) {
            this.selectionItemType = 'auto';
            let isChecked = selectItems.some((item) => {
              return item.id === this.selectInspection.id;
            });
            let index = this.templateModel.attributeIdList.findIndex((id) => id === this.selectInspection.id);
            //取消选中
            if (!isChecked) {
              let carrys = this._cloneDeep(this.templateModel.attributeIdList) || [];
              let carrys2 = this._cloneDeep(this.templateModel.attributeList) || [];
              carrys.splice(index, 1);
              carrys2.splice(index, 1);
              this.templateModel.attributeIdList = this._cloneDeep(carrys);
              this.templateModel.attributeList = this._cloneDeep(carrys2);
            } else {
              //选中
              if (index < 0) {
                this.templateModel.attributeIdList.push(this.selectInspection.id);
                this.templateModel.attributeList.push(this.selectInspection);
              }
            }
            // let isAllcancel = this.templateModel.attributeList.some((item) => {
            //   //item都不满足时，表示对模板的检验项都取消了勾选, 同时树结构的检验项也取消勾选
            //   return item.itemId === this.selectInspection.itemId;
            // });
            // // console.log(isAllcancel, 88877, this.templateModel.attributeList);
            // // selectItems.length === 0 ||
            // if (!isAllcancel) {
            //   //取消选中
            //   this.templateModel.itemIdList = this.templateModel.itemIdList.filter((id) => id != this.selectInspection.itemId);
            //   this.$refs.checkTreeProperties.setChecked(this.selectInspection.itemId, false);
            // } else {
            //   let index = this.templateModel.itemIdList.findIndex((id) => id === this.selectInspection.itemId);
            //   index < 0 ? this.templateModel.itemIdList.push(this.selectInspection.itemId) && this.$refs.checkTreeProperties.setChecked(this.selectInspection.itemId, true) : '';
            // }
          }

          clearTimeout(this.timer);
        }, 200);
      }
    },
    selectAll(list) {
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this._forEach(this.itemData, (item) => {
          let index = this.templateModel.attributeIdList.findIndex((id) => id === item.id);
          if (list.length === 0) {
            let carrys = this._cloneDeep(this.templateModel.attributeIdList) || [];
            let carrys2 = this._cloneDeep(this.templateModel.attributeList) || [];
            carrys.splice(index, 1);
            carrys2.splice(index, 1);
            this.templateModel.attributeIdList = this._cloneDeep(carrys);
            this.templateModel.attributeList = this._cloneDeep(carrys2);
          } else {
            if (index < 0) {
              this.templateModel.attributeIdList.push(item.id);
              this.templateModel.attributeList.push(item);
            }
          }
        });
        clearTimeout(this.timer);
      }, 200);
    },
    //通过检验项id及模板id查询检验明细
    getInspectionItems(itemId, templateId) {
      return getSelectattributeList({ itemId, templateId });
    },

    //下一步
    nextStep() {
      if (this.templateModel.attributeList.length <= 0) {
        this.$message.warning('请至少选择一条检验明细');
        return;
      }
      let column = this._cloneDeep(this.itemOption.column);
      this.sortableOption.column = [
        {
          label: '11',
          prop: 'icon',
          width: 50,
          slot: true
        },
        ...column
      ];
      let itemName = this.findObject(this.sortableOption.column, 'itemName');
      let attributeName = this.findObject(this.sortableOption.column, 'attributeName');
      let code = this.findObject(this.sortableOption.column, 'code');
      itemName.search = false;
      attributeName.search = false;
      code.search = false;
      this.sortableData = this._map(this._cloneDeep(this.templateModel.attributeList), (item) => {
        item.controlType = typeof item.controlType === 'string' ? JSON.parse(item.controlType) : item.controlType;
        let controlType = this.controlTypes.find((type) => type.dictKey === item.controlType.type);
        item.controlTypeLabel = (controlType && controlType.dictValue) || '';
        return item;
      });
      console.log(this.sortableData, 2232);
      this.sortableDialog = true;
    },

    //保存检验模板配置的检查项及明细
    saveTemplateAttributes() {
      // console.log(this.sortableData, 333333333333);
      if (this.sortableData.length > 0) {
        let attribute = this._cloneDeep(this.templateModel);
        let itemIdList = [];
        this._forEach(this.sortableData, (item, idx) => {
          if (!itemIdList.includes(item.itemId)) {
            itemIdList.push(item.itemId);
          }
        });
        attribute.itemIdList = itemIdList.reverse();
        attribute.attributeIdList = this._map(this.sortableData, (item) => item.id);
        delete attribute.attributeList;
        saveInspection(attribute).then(async (result) => {
          if (result.data.code === 200) {
            // let templateAttributes = await getSelectattributeList({ inspectionTemplateId: this.templateModel.templateId, itemType: this.itemType });
            // this.templateModel.attributeIdList = templateAttributes.data.data.filter((item) => item.checked).map((item) => item.id);
            this.sortableDialog = false;
            this.showCheckDialog = false;

            // // this.showTemplateDialog = true;
            this.fullscreenTemplateDialog = false;
            // this.attributeData = [];
            // this.selectItemId = '';
            // this.expandedAttributeKeys = [];
            // this.initSelectTree({ inspectionTemplateId: attribute.templateId });
          }
        });
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }
    },

    //加载模板对应的检验项树
    initSelectTree(params) {
      getInspectionlist(params).then((selectInspectionlist) => {
        selectInspectionlist = selectInspectionlist.data.data || [];
        let children = selectInspectionlist.map((item) => {
          return {
            id: item.id,
            label: item.itemName,
            leaf: false,
            value: item
          };
        });
        this.selectTreeData = [
          {
            id: '0000000',
            label: '检验项',
            value: {},
            leaf: true,
            children
          }
        ];
        if (this.selectItemId) {
          this.$nextTick(() => {
            this.expandedAttributeKeys = [].concat([this.selectItemId]);
            this.$refs.treeProperties.setCurrentKey(`${this.selectItemId}`);
            this.initAttributeList({
              itemId: this.selectItemId,
              inspectionTemplateId: this.templateModel.templateId
            });
          });
        } else {
          this.attributeData = [];
        }
      });
    },
    //取消保存检验模板配置的检查项及明细
    cancelSaveTemplateAttributes2() {
      this.sortableDialog = false;
      // this.templateModel = {
      //   attributeIdList: [],
      //   itemIdList: [],
      //   templateId: ''
      // };
    },
    cancelSaveTemplateAttributes() {
      this.showCheckDialog = false;
      this.templateModel = {
        attributeIdList: [],
        itemIdList: [],
        templateId: ''
      };
    },
    //树点击展示该项
    async nodeClick(data) {
      this.itemQuery = {
        itemId: data.id
      };
      this.newKey();
      if (data.leaf) {
        this.getInspectionItemData(this.itemQuery, { itemId: data.id });
        // let result = await getInspectionitemattributeList({ itemId: data.id });
        // this.itemData = ((result.data && result.data.data) || []).map((item) => {
        //   item.controlType = JSON.parse(item.controlType);
        //   let controlType = this.controlTypes.find((type) => type.dictKey === item.controlType.type);
        //   item.controlTypeLabel = (controlType && controlType.dictValue) || '';
        //   return item;
        // });
        // let selectData = this._intersectionWith(this.itemData, this.templateModel.attributeIdList, (item, attrId) => {
        //   return item.id === attrId;
        // });
        // this.$nextTick(() => {
        //   selectData.forEach((row) => {
        //     this.$refs.inspectionProperties.toggleRowSelection(row);
        //   });
        // });
      } else {
        this.itemData = [];
      }
    },

    //模板选中的检验详情树
    async selectTreeNodeClick(data) {
      if (!data.leaf) {
        this.selectItemId = data.id;
        this.initAttributeList({
          itemId: data.id,
          inspectionTemplateId: this.templateModel.templateId
        });
      } else {
        this.attributeData = [];
      }
    },

    //模板检验项新增检验明细
    addAttribute() {
      this.attributeTitle = '添加检验明细项';
      this.showAttributeDialog = true;
      this.fullscreenAttributeDialog = false;
      this.$nextTick(() => {
        this.$refs.attributeProperties.resetForm();
        this.attributeTemplateModel = Object.assign(
          {},
          {
            controlType: {
              type: '',
              options: []
            }
          }
        );
        this.attributeTemplateModel.controlType.options = [];
      });
    },
    //模板检验项更细检验明细
    updateAttribute() {
      if (this.selectionAttributeList.length === 1) {
        this.findAttribute(this.selectionAttributeList[0].id);
      }
    },
    //根据id查看检验明细详情
    findAttribute(id) {
      getInspectionitemattributeDetail({ id }).then((res) => {
        this.attributeTemplateModel = Object.assign({}, res.data.data);
        if (this.attributeTemplateModel.controlType) {
          this.attributeTemplateModel.controlType = JSON.parse(this.attributeTemplateModel.controlType);
        }
        this.attributeTitle = '更新检验明细项';
        this.showAttributeDialog = true;
        this.fullscreenAttributeDialog = false;
      });
    },

    closeDialog() {
      this.showTemplateDialog = false;
      this.showCheckDialog = true;
      this.fullscreenCheckDialog = false;
    },

    //取消展示模板检验项详情
    cancelShowTemplateDetail() {
      this.showTemplateDialog = false;
    },
    //模板检验项删除检验明细
    deleteAttribute() {
      if (this.selectionAttributeList.length > 0) {
        this.$confirm(`确定将数据删除?`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = this.selectionAttributeList.map((item) => item.id);
          removeInspectionitem(ids).then((res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.initAttributeList({
              itemId: this.selectItemId,
              inspectionTemplateId: this.templateModel.templateId
            });
          });
        });
      }
    },
    //加载模板对应的检验项选中的检验明细
    initAttributeList(params) {
      getInspectionitemattributeList(params).then((result) => {
        this.attributeData = (result.data.data || []).map((item) => {
          // item.controlType = JSON.parse(item.controlType);
          let controlType = this.controlTypes.find((type) => type.dictKey === item.controlType.type);
          item.controlTypeLabel = (controlType && controlType.dictValue) || '';
          return item;
        });
      });
    },

    //新增或修改子项
    async submitAttribute() {
      if (this.attributeTitle === '添加检验明细项') {
        delete this.attributeTemplateModel.id;
      }

      let attribute = this._cloneDeep(this.attributeTemplateModel);
      attribute.itemId = this.selectItemId;
      attribute.inspectionTemplateId = this.templateModel.templateId;
      attribute.controlType = JSON.stringify(attribute.controlType);
      attribute.checked = true;
      let done;
      let validDate = await new Promise((resolve, reject) => {
        this.$refs.attributeProperties.validate((valid, done) => {
          done = done;
          if (valid) {
            resolve();
            done();
          } else {
          }
        });
      });
      Promise.all([validDate]).then(() => {
        addInspectionitem(attribute).then(
          () => {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.initAttributeList({ itemId: this.selectItemId, inspectionTemplateId: this.templateModel.templateId });
            this.showAttributeDialog = false;
            this.$refs.attributeProperties.resetForm();
            this.controlTypeOptions = Object.assign(
              {},
              {
                //存储不同类型组件options
                inputOptions: [],
                radioOptions: [],
                multipleOptions: []
              }
            );
            this.attributeTemplateModel = {
              controlType: {
                type: '',
                options: []
              }
            };
          },
          (error) => {
            window.console.log(error);
          }
        );
        done();
      });
    },

    //刷新模板对应的检验树
    refreshInspection() {
      this.initSelectTree({ inspectionTemplateId: this.templateModel.templateId });
    },
    //模板新增检验项
    addInspection() {
      this.showInspectionDialog = true;
      this.fullscreenInspectionDialog = false;
      this.inspectionTitle = '添加检验项';
      this.inspectionModel = {};
      this.controlTypeOptions = Object.assign(
        {},
        {
          //存储不同类型组件options
          inputOptions: [],
          radioOptions: [],
          multipleOptions: []
        }
      );
    },
    //模板更新检验项
    updateInspection() {
      this.controlTypeOptions = Object.assign(
        {},
        {
          //存储不同类型组件options
          inputOptions: [],
          radioOptions: [],
          multipleOptions: []
        }
      );
      if (this.selectItemId) {
        getInspectionDetail({ id: this.selectItemId }).then((res) => {
          this.inspectionModel = res.data.data;
          this.inspectionTitle = '修改检验项';
          this.showInspectionDialog = true;
          this.fullscreenInspectionDialog = false;
        });
      }
    },
    //删除模板检验项
    removeInspection() {
      if (this.selectItemId) {
        this.$confirm(`确定将数据删除?`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delInspection([this.selectItemId]).then((res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.selectItemId = '';
            this.initSelectTree({ inspectionTemplateId: this.templateModel.templateId });
          });
        });
      }
    },
    newKey() {
      this.key = new Date().getTime();
    },
    async submitInspection() {
      let attribute = this.inspectionModel;
      attribute.inspectionTemplateId = this.templateModel.templateId;
      let done;
      let validDate = await new Promise((resolve, reject) => {
        this.$refs.inspectionTemplateProperties.validate((valid, done) => {
          done = done;
          if (valid) {
            resolve();
            done();
          } else {
          }
        });
      });
      Promise.all([validDate]).then(() => {
        addOrUpdateInspection(attribute).then(
          (res) => {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.inspectionModel = {};
            this.initSelectTree({ inspectionTemplateId: this.templateModel.templateId });
            this.$refs.inspectionTemplateProperties.resetForm();
            this.showInspectionDialog = false;
          },
          (error) => {
            window.console.log(error);
          }
        );
        done();
      });
    },
    cancelInspection() {
      this.showInspectionDialog = false;
    },

    //取消
    cancelAttribute() {
      this.showAttributeDialog = false;
      this.attributeTemplateModel = {
        controlType: {
          type: '',
          options: []
        }
      };
    },

    //添加控件类型的子项
    addOption(type) {
      type === 'SINGLE-INPUT'
        ? this.attributeTemplateModel.controlType.options.push({
            label: '',
            type: ''
          })
        : this.attributeTemplateModel.controlType.options.push({
            label: '',
            type: '',
            realLabel: '是',
            shamLabel: '否'
          });
    },

    changeControlType(val) {
      let controlType = this.attributeTemplateModel.controlType.options.length > 0 ? this.attributeTemplateModel.controlType.options[0].controlType : '';

      switch (controlType) {
        case 'SINGLE-INPUT':
          this.controlTypeOptions.inputOptions = this.attributeTemplateModel.controlType.options || [];
          break;
        case 'MULTIPLE-INPUT':
          this.controlTypeOptions.multipleOptions = this.attributeTemplateModel.controlType.options || [];
          break;
        case 'RADIO':
          this.controlTypeOptions.radioOptions = this.attributeTemplateModel.controlType.options || [];
          break;
      }
      switch (val) {
        case 'SINGLE-INPUT':
          this.controlTypeOptions.inputOptions.length == 0
            ? (this.attributeTemplateModel.controlType.options = [
                {
                  label: '',
                  type: '',
                  controlType: 'SINGLE-INPUT'
                }
              ])
            : (this.attributeTemplateModel.controlType.options = this._cloneDeep(this.controlTypeOptions.inputOptions));
          break;
        case 'MULTIPLE-INPUT':
          this.controlTypeOptions.multipleOptions.length == 0
            ? (this.attributeTemplateModel.controlType.options = [
                {
                  label: '',
                  type: '',
                  controlType: 'MULTIPLE-INPUT'
                }
              ])
            : (this.attributeTemplateModel.controlType.options = this._cloneDeep(this.controlTypeOptions.multipleOptions));
          break;
        case 'RADIO':
          this.controlTypeOptions.radioOptions.length == 0
            ? (this.attributeTemplateModel.controlType.options = [
                {
                  label: '',
                  type: '',
                  realLabel: '是',
                  shamLabel: '否',
                  controlType: 'RADIO'
                }
              ])
            : (this.attributeTemplateModel.controlType.options = this._cloneDeep(this.controlTypeOptions.radioOptions));
          break;
        default:
          this.attributeTemplateModel.controlType.options = [];
      }
    },
    //删除某一项控件
    deletecontrolType(index) {
      this.attributeTemplateModel.controlType.options = this.attributeTemplateModel.controlType.options.filter((item, i) => index != i);
      this.attributeTemplateModel.controlType.options.length == 0 ? (this.attributeTemplateModel.controlType.type = '') : '';
    },

    openExample() {
      let showHtml = '';
      switch (this.attributeTemplateModel.controlType.type) {
        case 'SINGLE-INPUT':
          showHtml = ` <div><span>检验数量：</span> <div style="display:inline-block;float: right;font-size: 12px">请输入</div></div>
          <div><span>不良数量：</span> <div style="display:inline-block;float: right;font-size: 12px">请输入</div></div>`;
          break;
        case 'MULTIPLE-INPUT':
          showHtml = `<div><span>测试值：</span> <input/> <button style="background-color: #169bd5;color: #ffffff;border: 1px solid;margin-left:15px;border-radius:5px">确定</button></div>
         <div style="margin: 10px 0">   <table border="1">
    <tr>
        <th width=50 style="text-align: center">次数</th>
        <th width=70 style="text-align: center">测试值</th>
          <th width=120 style="text-align: center">测试结果</th>
          <th width=70 style="text-align: center">操作</th>
    </tr>
    <tr>
        <td style="text-align: center">1</td>
        <td style="text-align: center">12</td>
        <td style="text-align: center">
        <span><input checked type="radio"/>OK</span> <span><input type="radio"/>NG</span>
        </td>
          <td style="text-align: center;color:red"><div>x</div></td>
    </tr>
</table></div>`;
          break;
        case 'RADIO':
          showHtml = `<div><span>是否按标准检验:</span>   <div style="display:inline-block;margin-left: 21%">  <span style="margin-right: 20px"><input type="radio"/>是</span> <span><input type="radio"/>否</span></div></div>`;
          break;
      }
      this.$alert(
        `<div><span>检验项：外观情况</span></div>
         <div><span>检验明细项：划伤/变形/裂痕/松动</span></div>
         <div><span>检验标准：无伤痕、无变形、无裂痕、无松动</span></div>
         <div><span>检验工具：目测</span></div>
         ${showHtml}
          <div><span>检验结果：</span>   <div style="display:inline-block;margin-left: 29%">  <span style="margin-right: 20px"><input checked type="radio"/>OK</span> <span><input type="radio"/>NG</span></div></div>`,
        '',
        {
          dangerouslyUseHTMLString: true,
          showConfirmButton: false
        }
      );
    },

    cancel() {
      this.showDialog = false;
      this.model = {};
    },

    beforeOpen(done, type) {
      done();
    },
    searchReset() {
      this.onLoad(this.page);
    },
    searchItemChange(params, done) {
      this.itemQuery = params;
      delete this.itemQuery.itemId;
      this.getInspectionItemData(this.itemPage, params);
      done();
    },
    searchItemReset() {
      this.getInspectionItemData(this.itemPage);
    },
    searchChange(params, done) {
      if (params.sendExamineDate && params.sendExamineDate.length > 0) {
        params.startTime = params.sendExamineDate[0];
        params.endTime = this.$moment(this.$moment(params.sendExamineDate[1]).add(1, 'days')).format('YYYY-MM-DD');
      }
      delete params.sendExamineDate;
      params.status = 1;
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },

    selectionAttributeChange(list) {
      this.selectionAttributeList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    selectionItemClear() {
      this.$refs.inspectionProperties.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    currentItemChange(currentPage) {
      this.itemPage.currentPage = currentPage;
      this.getInspectionItemData(this.itemPage, this.itemQuery);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    sizeItemChange(pageSize) {
      this.itemPage.pageSize = pageSize;
      this.getInspectionItemData(this.itemPage, this.itemQuery);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        // [] || dataListTable
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    newKey() {
      this.key = new Date().getTime();
    },
    getSelectedRows(rowData) {
      if (this.modalName === 'ADD') {
        this.form.reportTemplateName = this._get(rowData, 'name', '');
        this.form.reportTemplateId = this._get(rowData, 'id', '');
      } else {
        this.model.reportTemplateName = this._get(rowData, 'name', '');
        this.model.reportTemplateId = this._get(rowData, 'id', '');
      }
    },
    openInspectionReportModal(title) {
      this.modalName = title;
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择检验报告模板（双击进行选择）',
        url: '/api/blade-report/report/rest/list',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '文件名',
            prop: 'name',
            search: true
          },
          {
            label: '创建时间',
            prop: 'createTime'
          },
          {
            label: '更新时间',
            prop: 'updateTime'
          }
        ]
      };
    }
  }
};
</script>

<style scoped lang="scss">
$BORDER-STYLE: 1px solid #f0f0f0 !important;
$size: 16px;
.refresh-item {
  background: #00bcd4;
}

.add-item {
  background: #4caf50;
}

.edit-item {
  background: #077fc1;
}

.del-item {
  background: #f44336;
}

.refresh-item,
.add-item,
.edit-item,
.del-item {
  margin-right: 8px;
  cursor: pointer;
  color: #ffffff;
}
.delete-controlType:hover {
  cursor: pointer;
}
.close-dialog {
  float: right;
  &:hover {
    cursor: pointer;
  }
}

.btn-fab-mini {
  width: 27px;
  height: 27px;
  min-width: 27px;
}
.inspection-btn {
  border-radius: 30px;
  width: 27px;
  height: 27px;
  min-width: 27px;
  margin-left: 2px !important;
  color: #fff;
  padding: 0;
  overflow: hidden;
  position: relative;
  line-height: normal;
  border: 1px solid;
}
.refresh-btn {
  background-color: #00bcd4;
}
.add-btn {
  background-color: #4caf50;
}
.edit-btn {
  background-color: #077fc1;
}
.btn-disabled {
  background-color: #dedede;
}
.del-btn {
  background-color: #f44336 !important;
}
.btn-icon {
  margin-right: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #ffffff;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-12px, -12px);
  line-height: 24px;
  width: 24px;
  vertical-align: middle;
}
.ripple-container {
  border-radius: 50%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 100%;
  overflow: hidden;
  border-radius: inherit;
  pointer-events: none;
}

::v-deep .inspection-btn:hover {
  background-color: #dedede;
}
::v-deep .el-dialog__header {
  border-bottom: $BORDER-STYLE;
}

::v-deep .el-dialog__footer {
  border-top: $BORDER-STYLE;
}
.fill-screen-edit-icon {
  color: #909399;
  font-size: 15px;
  padding-right: 10px;
  &:hover {
    color: #409eff;
  }
}

.fill-screen-icon {
  color: #909399;
  font-size: 15px;
  float: right;
  padding-right: 25px;
  &:hover {
    color: #409eff;
  }
}

.group-title {
  border-bottom: 1px solid rgb(240, 240, 240) !important;
  font-size: 16px;
  font-weight: 500;
  height: 50px;
  line-height: 50px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 20px;
}

.subTitle {
  font-size: 16px;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.85);
  .mr10 {
    margin-right: 10px;
  }
}
</style>
